package com.briup.ch12;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author briup-adam
 * @Date 2023/10/25 下午3:58
 * @Description 接收客户端发送的数据并发送数据给客户端
 * @see java.net.ServerSocket
 **/

public class TcpServerDemo1 {
    public static void main(String[] args) {
        try {
            //创建服务器
            ServerSocket server = new ServerSocket(10086);
            System.out.println("服务器已经创建等待客户端连接");
            //等待客户端来连接  这个方法会造成线程阻塞
            Socket socket = server.accept();
            System.out.println("有客户端来连接，IP：" + socket.getInetAddress());
            //接收客户端发送的数据
            InputStream is = socket.getInputStream();
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                System.err.println(new String(b, 0, len));
            }
            socket.getInputStream();
            System.out.println("客户端发送的消息已经接收完毕");
            //写回数据给客户端
            String msg = "海内存知己天涯若比邻。再见！";
            OutputStream os = socket.getOutputStream();
            os.write(msg.getBytes());
            socket.shutdownOutput();
            //关闭socket
            socket.close();
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
